package com.elm.dao;

import com.elm.entity.Cart;
import com.elm.entity.OrderDetailet;
import com.elm.entity.Orders;
import com.elm.util.DBUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class OrderDao {
    private final CartDao cartDao;
    private final OrderDetailetDao orderDetailetDao;
    public OrderDao() {
        this.cartDao = new CartDao();
        this.orderDetailetDao = new OrderDetailetDao();
    }

    public int createOrders(Orders orders) throws SQLException {
        Connection connection = null;
        try {
            connection = DBUtil.getConnection();
            // 关闭自动提交，开启事务
            connection.setAutoCommit(false);

            String sql = "insert into orders(userId, businessId, orderDate, orderTotal, daId) values(?,?,?,?,?)";
            try (PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
                ps.setString(1, orders.getUserId());
                ps.setInt(2, orders.getBusinessId());
                ps.setString(3, orders.getOrderDate());
                ps.setDouble(4, orders.getOrderTotal());
                ps.setInt(5, orders.getDaId());

                int affectedRows = ps.executeUpdate();
                if (affectedRows == 0) {
                    throw new SQLException("Creating order failed, no rows affected.");
                }

                try (ResultSet generatedKeys = ps.getGeneratedKeys()) {
                    if (generatedKeys.next()) {
                        int orderId = generatedKeys.getInt(1);
                        //创建订单详情 -- 根据从购物车中取出
                        String userId = orders.getUserId();
                        int businessId = orders.getBusinessId();

                        List<Cart> carts = cartDao.getCartListByUserIdAndBusinessId(userId, businessId);
                        List<OrderDetailet> orderDetailets = new ArrayList<>();
                        for (Cart cart : carts) {
                            OrderDetailet orderDetailet = new OrderDetailet();
                            orderDetailet.setOrderId(orderId);
                            orderDetailet.setQuantity(cart.getQuantity());
                            orderDetailet.setFoodId(cart.getFoodId());

                            orderDetailets.add(orderDetailet);
                        }

                        orderDetailetDao.saveOrderDetailet(orderDetailets);
                        // 提交事务
                        connection.commit();
                        return orderId;
                    } else {
                        // 回滚事务（关键点：获取ID失败时撤销插入）
                        connection.rollback();
                        throw new SQLException("Creating order failed, no ID obtained.");
                    }
                }
            }
        } catch (SQLException e) {
            // 异常时回滚事务
            if (connection != null) {
                connection.rollback();
            }
            throw e;
        } finally {
            // 确保连接关闭和状态恢复
            if (connection != null) {
                try {
                    connection.setAutoCommit(true); // 恢复自动提交模式
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public List<Orders> getOrdersListByUserId(String userId) {
        String sql="select * from orders where userId=?";
        List<Orders> list = new ArrayList<Orders>();
        try(Connection connection = DBUtil.getConnection();
            PreparedStatement ps = connection.prepareStatement(sql)) {
            ps.setString(1, userId);
            ResultSet rs = ps.executeQuery();
            while(rs.next()) {
                Orders orders = new Orders();
                orders.setUserId(rs.getString("userId"));
                orders.setBusinessId(rs.getInt("businessId"));
                orders.setOrderDate(rs.getString("orderDate"));
                orders.setOrderTotal(rs.getDouble("orderTotal"));
                orders.setDaId(rs.getInt("daId"));
                orders.setOrderId(rs.getInt("orderId"));
                orders.setOrderState(rs.getInt("orderState"));

                list.add(orders);
            }
            return list;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public Orders getOrdersById(String orderId) throws SQLException {
        String sql="select * from orders where orderId=?";
        Orders orders = new Orders();

        try(Connection connection = DBUtil.getConnection();
            PreparedStatement ps = connection.prepareStatement(sql)) {
            ps.setString(1, orderId);
            ResultSet rs = ps.executeQuery();
            if(rs.next()) {
                orders.setUserId(rs.getString("userId"));
                orders.setBusinessId(rs.getInt("businessId"));
                orders.setOrderDate(rs.getString("orderDate"));
                orders.setOrderTotal(rs.getDouble("orderTotal"));
                orders.setDaId(rs.getInt("daId"));
                orders.setOrderId(rs.getInt("orderId"));
                orders.setOrderState(rs.getInt("orderState"));
            }
            return orders;
        }catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
